package com.smartfast4j.manager.common.interceptor;

import com.alibaba.fastjson.JSON;
import com.smartfast4j.common.Constants;
import com.smartfast4j.common.bean.R;
import com.smartfast4j.common.component.cache.CacheService;
import com.smartfast4j.common.util.WebUtil;
import com.smartfast4j.manager.common.bean.LoginUserInfo;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;

/**
 * 登录拦截器
 */
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {

    private static final Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

    @Autowired
    private CacheService cacheService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod)) {
            return super.preHandle(request, response, handler);
        }
        logger.debug(">>>LoginInterceptor>>>>>>>登录拦截器");
        String reqUrl = request.getRequestURL().toString();
        logger.debug(">>>LoginInterceptor>>>>>>>访问的URL："+reqUrl);
        String token = request.getParameter("token");
        //从缓存中获取当前登录的系统用户
        LoginUserInfo loginUser = cacheService.get(Constants.LOGIN_USER.TOKEN_PREFIX+token);
        if(loginUser == null){//用户未登录
            //1.判断是否为ajax请求
            String ajaxRequest = request.getHeader("ajaxRequest");//自定义AJAX请求头，用于标识是否为ajax请求
            if (StringUtils.isNotEmpty(ajaxRequest) && Boolean.valueOf(ajaxRequest)) {
                logger.debug("----本次请求为AJAX请求-----");
                response.setHeader("loginStatus", "timeout");//在响应头设置登录状态
            }else{
                logger.debug("----本次请求为普通请求-----");
                WebUtil.writeJsonRes(JSON.toJSONString(R.fail("用户未登录")),response);
            }
            return false;
        }
        return super.preHandle(request, response, handler);
    }
}
